#include"SList.h"

//链表的打印
void SListPrint(SListNode* plist)
{
	SListNode* cur = plist;
	while (cur != NULL)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

//创建新结点
SListNode* BuySListNode(SListDataType x)
{
	SListNode* node = (SListNode*)malloc(sizeof(SListNode));
	node->data = x;
	node->next = NULL;

	return node;
}

//尾插
void SListPushBack(SListNode** pplist, SListDataType x)
{
	SListNode* newnode = BuySListNode(x);

	if (*pplist == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		SListNode* tail = *pplist;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

//头插
void SListPushFront(SListNode** pplist, SListDataType x)
{
	SListNode* newnode = BuySListNode(x);

	newnode->next = *pplist;
	*pplist = newnode;
}

//尾删
void SListPopBack(SListNode** pplist)
{
	if (*pplist == NULL)
	{
		return;
	}
	else if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist=NULL;
	}
	else
	{
		SListNode* prev = NULL;
		SListNode* tail = *pplist;
		while (tail->next != NULL)
		{
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;

		prev->next = NULL;
	}
}

//头删
void SListPopFront(SListNode** pplist)
{
	if (*pplist == NULL)
	{
		return;
	}
	else
	{
		SListNode* next = (*pplist)->next;
		free(*pplist);

		*pplist = next;
	}
}

//查找
SListNode* SListFind(SListNode* plist, SListDataType x)
{
	SListNode* cur = plist;
	while (cur != NULL)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur=cur->next;
	}
	return NULL;
}

//在pos之后插入
void SListInsertAfter(SListNode* pos, SListDataType x)
{
	assert(pos);

	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

//在pos之前插入
void SListInsertBefore(SListNode** pplist, SListNode* pos, SListDataType x)
{
	assert(pos);

	SListNode* newnode = BuySListNode(x);

	if (pos == *pplist)
	{
		newnode->next = pos;
		*pplist = newnode;
	}
	else
	{
		SListNode* prev = NULL;
		SListNode* cur = *pplist;
		while (cur != pos)
		{
			prev = cur;
			cur = cur->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}

//在pos之后删除
void SListEraseAfter(SListNode* pos)
{
	assert(pos);

	if (pos->next == NULL)
	{
		return;
	}
	else
	{
		SListNode* next = pos->next;
		pos->next = next->next;
		free(next);
		next = NULL;
	}
}

//删除当前位置
void SListEraseCur(SListNode** pplist, SListNode* pos)
{
	assert(pos);

	if (pos == *pplist)
	{
		*pplist = pos->next;
		free(pos);
	}
	else
	{
		SListNode* prev = NULL;
		SListNode* cur = *pplist;
		while (cur != pos)
		{
			prev = cur;
			cur = cur->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}